package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"go-agent/pkg/collector"
	"go-agent/pkg/config"
	"go-agent/pkg/logger"
)

func main() {
	// 初始化日志
	if err := logger.Init(true); err != nil {
		log.Fatalf("初始化日志失败: %v", err)
	}

	fmt.Println("=== 测试 Nginx 和 Zookeeper 采集器 ===")

	// 测试Nginx采集器
	testNginxCollector()

	// 测试Zookeeper采集器
	testZookeeperCollector()

	// 测试内置监控项配置匹配
	testBuiltinItemsMapping()
}

func testNginxCollector() {
	fmt.Println("\n--- 测试 Nginx 采集器 ---")

	// 创建Nginx采集器配置
	nginxConfig := collector.NginxConfig{
		Enabled:       true,
		StatusURL:     "http://127.0.0.1/nginx_status", // 需要配置nginx status模块
		Timeout:       10,
		SlowThreshold: 500,
		UserAgent:     "go-agent-test/1.0",
		Headers:       make(map[string]string),
	}

	// 创建采集器
	nginxCollector := collector.NewNginxCollector(nginxConfig)

	// 执行采集
	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()

	fmt.Printf("正在采集 Nginx 指标从: %s\n", nginxConfig.StatusURL)
	metrics, err := nginxCollector.Collect(ctx)
	if err != nil {
		fmt.Printf("❌ Nginx 采集失败: %v\n", err)
		fmt.Printf("提示: 请确保 Nginx 已安装并启用了 status 模块\n")
		fmt.Printf("配置示例:\n")
		fmt.Printf("  server {\n")
		fmt.Printf("    location /nginx_status {\n")
		fmt.Printf("      stub_status on;\n")
		fmt.Printf("      access_log off;\n")
		fmt.Printf("      allow 127.0.0.1;\n")
		fmt.Printf("      deny all;\n")
		fmt.Printf("    }\n")
		fmt.Printf("  }\n")
	} else {
		fmt.Printf("✅ Nginx 采集成功!\n")
		fmt.Printf("  活动连接数: %d\n", metrics.ActiveConnections)
		fmt.Printf("  响应时间: %.2f ms\n", metrics.ResponseTime)
		fmt.Printf("  服务器接受连接数: %d\n", metrics.ServerAccepts)
		fmt.Printf("  服务器处理连接数: %d\n", metrics.ServerHandled)
		fmt.Printf("  服务器处理请求数: %d\n", metrics.ServerRequests)
		fmt.Printf("  正在读取: %d\n", metrics.Reading)
		fmt.Printf("  正在写入: %d\n", metrics.Writing)
		fmt.Printf("  等待连接: %d\n", metrics.Waiting)

		// 测试指标值提取
		testNginxMetricValues(nginxCollector, metrics)
	}

	// 关闭采集器
	nginxCollector.Close()
}

func testNginxMetricValues(collector *collector.NginxCollector, metrics *collector.NginxMetrics) {
	fmt.Println("\n  测试 Nginx 指标值提取:")

	testPaths := []string{
		"Connections.Active",
		"Request.Time",
		"Response.Time",
		"Response.LastSize",
		"Response.Slow",
	}

	for _, path := range testPaths {
		value := collector.GetMetricValue(metrics, path)
		fmt.Printf("    %s: %v\n", path, value)
	}
}

func testZookeeperCollector() {
	fmt.Println("\n--- 测试 Zookeeper 采集器 ---")

	// 创建Zookeeper采集器配置
	zookeeperConfig := collector.ZookeeperConfig{
		Enabled:        true,
		Host:           "127.0.0.1",
		Port:           2181,
		Timeout:        10,
		Commands:       []string{"stat", "conf", "envi"},
		TrackHistory:   true,
		MaxHistorySize: 10,
	}

	// 创建采集器
	zookeeperCollector := collector.NewZookeeperCollector(zookeeperConfig)

	// 执行采集
	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()

	fmt.Printf("正在采集 Zookeeper 指标从: %s:%d\n", zookeeperConfig.Host, zookeeperConfig.Port)
	metrics, err := zookeeperCollector.Collect(ctx)
	if err != nil {
		fmt.Printf("❌ Zookeeper 采集失败: %v\n", err)
		fmt.Printf("提示: 请确保 Zookeeper 服务已启动并监听在 %s:%d\n",
			zookeeperConfig.Host, zookeeperConfig.Port)
		fmt.Printf("Zookeeper 需要启用四字命令支持，在配置文件中添加:\n")
		fmt.Printf("  4lw.commands.whitelist=stat,conf,envi,srvr\n")
	} else {
		fmt.Printf("✅ Zookeeper 采集成功!\n")
		fmt.Printf("  连接客户端数: %d\n", metrics.ClientConnected)
		fmt.Printf("  响应时间: %.2f ms\n", metrics.ResponseTime)
		fmt.Printf("  最后响应大小: %d bytes\n", metrics.ResponseSizeLast)
		fmt.Printf("  最大响应大小: %d bytes\n", metrics.ResponseSizeMax)
		fmt.Printf("  平均延迟: %.2f ms\n", metrics.AvgLatency)
		fmt.Printf("  最大延迟: %.2f ms\n", metrics.MaxLatency)
		fmt.Printf("  ZNode数量: %d\n", metrics.ZnodeCount)
		fmt.Printf("  服务器状态: %s\n", metrics.ServerState)
		fmt.Printf("  版本: %s\n", metrics.Version)
		fmt.Printf("  缓存启用: %d\n", metrics.CacheEnabled)

		// 测试指标值提取
		testZookeeperMetricValues(zookeeperCollector, metrics)
	}

	// 关闭采集器
	zookeeperCollector.Close()
}

func testZookeeperMetricValues(collector *collector.ZookeeperCollector, metrics *collector.ZookeeperMetrics) {
	fmt.Println("\n  测试 Zookeeper 指标值提取:")

	testPaths := []string{
		"Response.Time",
		"Response.LastSize",
		"Response.MaxSize",
		"Clients.Connected",
		"Cache.Enabled",
	}

	for _, path := range testPaths {
		value := collector.GetMetricValue(metrics, path)
		fmt.Printf("    %s: %v\n", path, value)
	}
}

func testBuiltinItemsMapping() {
	fmt.Println("\n--- 测试内置监控项配置匹配 ---")

	// 加载配置
	cfg, err := config.Load("configs/config.yaml")
	if err != nil {
		fmt.Printf("❌ 加载配置失败: %v\n", err)
		return
	}

	fmt.Printf("✅ 配置加载成功\n")
	fmt.Printf("  Nginx 采集启用: %t\n", cfg.Collect.Nginx.Enabled)
	fmt.Printf("  Nginx 状态URL: %s\n", cfg.Collect.Nginx.StatusURL)
	fmt.Printf("  Zookeeper 采集启用: %t\n", cfg.Collect.Zookeeper.Enabled)
	fmt.Printf("  Zookeeper 主机: %s:%d\n", cfg.Collect.Zookeeper.Host, cfg.Collect.Zookeeper.Port)

	// 测试内置监控项匹配
	fmt.Println("\n  测试内置监控项键值匹配:")

	nginxItems := []string{
		"nginx.connections.active",
		"nginx.request.time",
		"nginx.response.slow",
		"nginx.response.size",
	}

	zookeeperItems := []string{
		"zookeeper.response.size.last",
		"zookeeper.response.size.max",
		"zookeeper.client.connected",
		"zookeeper.response.time",
		"zookeeper.cache.enabled",
	}

	fmt.Printf("  Nginx 监控项:\n")
	for _, item := range nginxItems {
		fmt.Printf("    - %s\n", item)
	}

	fmt.Printf("  Zookeeper 监控项:\n")
	for _, item := range zookeeperItems {
		fmt.Printf("    - %s\n", item)
	}
}